//
//  LoginVModel.swift
//  DadaSolusi
//
//  Created by liyahao on 2025/9/9.
//

import Foundation
import SwiftUI
import Combine
import AppTrackingTransparency
import AdSupport

// MARK: - LoginViewModel
class LoginVModel: BaseVModel<LoginModel> {
    @Published var phoneNumber = ""
    @Published var verificationCode = ""
    @Published var countdownTime = 0
    @Published var canSendCode = true
    @Published var showToast = false
    @Published var toastMessage = ""
    
    private var timer: Timer?
    private let userDefaults = UserDefaults.standard
    private var cancellables = Set<AnyCancellable>()
    
    // Keys for UserDefaults
    private let phoneNumberKey = "savedPhoneNumber"
    private let sendCodeTimeKey = "sendCodeTime"
    private let loginSuccessTimeKey = "loginSuccessTime"
    
    var countdownText: String {
        if countdownTime > 0 {
            return "\(countdownTime)s"
        } else {
            return "Send Code"
        }
    }
    
    // MARK: - IDFA Request
    func requestIDFA() {
        if #available(iOS 14, *) {
            ATTrackingManager.requestTrackingAuthorization { status in
                DispatchQueue.main.async {
                    self.reportIDFA()
                }
            }
        } else {
            reportIDFA()
        }
    }
    
    private func reportIDFA() {
        let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
        NetManager.idfa(idfa: idfa) { result in
            
        }
    }
    
    // MARK: - Location Manager Setup
    private func setupLocationManager() {
        LocationManager.shared.startUpdatingLocation()
    }
    
    // MARK: - Load Saved Phone Number
    func loadSavedPhoneNumber() {
        if let savedPhone = userDefaults.string(forKey: phoneNumberKey) {
            phoneNumber = savedPhone
        }
    }
    
    // MARK: - Send Verification Code
    func sendVerificationCode() {
        guard canSendCode else { return }
        
        // Save send code time
        userDefaults.set(Date().timeIntervalSince1970, forKey: sendCodeTimeKey)
        
        // Call API
        NetManager.serp(serp: phoneNumber) { result in
            switch result {
            case .Success(let model):
                if model.success {
                    // Save phone number
                    self.userDefaults.set(self.phoneNumber, forKey: self.phoneNumberKey)
                    // Save login success time
                    self.userDefaults.set(Date().timeIntervalSince1970, forKey: self.loginSuccessTimeKey)
                    // Request location permission
                    self.setupLocationManager()
                    // Navigate to home or show success
                    self.toast = "Login successful!"
                } else {
                    self.toast = model.herbive
                }
            case .Fail(let code, let error):
                self.toast = error.debugDescription
            default:
                print("default")
            }
        }
    }
    
    // MARK: - Login
    func login() {
        NetManager.login(amoracity: phoneNumber, agency: verificationCode) { result in
            switch result {
            case .Success(let response):
                if response.success {
                    // Save phone number
                    self.userDefaults.set(self.phoneNumber, forKey: self.phoneNumberKey)
                    // Save login success time
                    self.userDefaults.set(Date().timeIntervalSince1970, forKey: self.loginSuccessTimeKey)
                    // Request location permission
                    self.setupLocationManager()
                    // Navigate to home or show success
                    self.toast = "Login successful!"
                } else {
                    self.toast = response.herbive
                }
            case .Fail(let code, let error):
                self.toast = error.debugDescription
            default:
                print("default")
            }
        }
    }
    
    // MARK: - Countdown Timer
    private func startCountdown() {
        canSendCode = false
        countdownTime = 60
        
        timer?.invalidate()
        timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in
            guard let self = self else { return }
            
            if self.countdownTime > 0 {
                self.countdownTime -= 1
            } else {
                self.timer?.invalidate()
                self.canSendCode = true
            }
        }
    }
    
    // MARK: - Toast Message
    private func showToastMessage(_ message: String) {
        toastMessage = message
        showToast = true
        
        // Hide toast after 3 seconds
        DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
            self.showToast = false
        }
    }
    
    // MARK: - Get Saved Times for Tracking
    func getSavedTimes() -> (sendCodeTime: TimeInterval?, loginTime: TimeInterval?) {
        let sendTime = userDefaults.object(forKey: sendCodeTimeKey) as? TimeInterval
        let loginTime = userDefaults.object(forKey: loginSuccessTimeKey) as? TimeInterval
        return (sendTime, loginTime)
    }
    
    func clearSavedTimes() {
        userDefaults.removeObject(forKey: sendCodeTimeKey)
        userDefaults.removeObject(forKey: loginSuccessTimeKey)
    }
    
    deinit {
        timer?.invalidate()
    }
}
